package net.zjitc.arrays;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TripMat {
    //行，列，三元组元素
    private int row;
    private int col;
    private List<Triple> list;

    public TripMat() {
        list = new ArrayList<>();
    }

    /**
     * 矩阵压缩
     * @param arr 二维数组
     */
    public void compress(int[][] arr){

        row = arr.length;
        col = arr[0].length;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[i][j] != 0){
                    list.add(new Triple(i,j,arr[i][j]));
                }
            }
        }
    }

    /**
     * 解压成二维数组
     * @return 二维数组
     */

    public int[][] decompression(){
      int[][] temp = new int[row][col];
       //方法一
        for (int i = 0; i < list.size(); i++) {
            Triple triple = list.get(i);
            temp[triple.getRow()][triple.getCol()] = triple.getValue();
        }
      //方法二
        for (Triple triple: list) {
            temp[triple.getRow()][triple.getCol()] = triple.getValue();
        }
        //方法三
        Iterator<Triple> iterator = list.iterator();
        while (iterator.hasNext()){
            Triple triple = iterator.next();
            temp[triple.getRow()][triple.getCol()] = triple.getValue();
        }

        return temp;
    }
}
